const CryptoJS = require('./aes.js'); //引用AES源码js
import WxmpRsa from "wxmp-rsa";

var RandomKey = randomString(16);
const PublicKey =
  "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqHNIDYt7gpyEX1zZiMFjbtBgjnj6ybYvqoMvotMnxxnEot9AVGT45ks85mHoyuxaf2pm+iHWRCUeWMv+WkAE9/vCwcxvF8jVzXeKmnSkfdKDpPzyiM0VaGeT+hGa/3E09eMvUZt4do88hvhGyNDKkKKNlgWK1OIJI3j6SzcPdqQIDAQAB-----END PUBLIC KEY-----";
const RSA = new WxmpRsa();
RSA.setPublicKey(PublicKey);
var Sign = RSA.encryptLong(RandomKey);

/**
 * aes 解密方法
 */
 export function AesDecrypt(word, keysting) {
  const key = CryptoJS.enc.Utf8.parse(keysting); //十六位十六进制数作为秘钥
  const iv = CryptoJS.enc.Utf8.parse(keysting);//十六位十六进制数作为秘钥偏移量
  // let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
  // let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(word, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
/**
 * aes 加密方法
 */
export function AesEncrypt(word, keysting) {
  const key = CryptoJS.enc.Utf8.parse(keysting); //十六位十六进制数作为秘钥
  const iv = CryptoJS.enc.Utf8.parse(keysting);//十六位十六进制数作为秘钥偏移量
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString().toUpperCase();
}

/**
 * base64 加密方法
 */
function Base64Encode(val) {
  let str = CryptoJS.enc.Utf8.parse(val);
  let base64 = CryptoJS.enc.Base64.stringify(str);
  return base64;
}

/**
 * base64 解密方法
 */
function Base64Decode(val) {
  let words = CryptoJS.enc.Base64.parse(val);
  return words.toString(CryptoJS.enc.Utf8);
}

export function randomString(len) {
  len = len || 32;
  var $chars = "0123456789ABCDEF";
  var maxPos = $chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}


export function getRandomKey() {
  return RandomKey
}

export function getSign() {
  return Sign
}

// //暴露接口
// module.exports = {
//   AesEncrypt,
//   AesDecrypt,
//   Base64Encode,
//   Base64Decode,
//   randomString,
//   getRandomKey,
//   getSign,
// };